



User-defined Custom Exception in Java


Java provides us facility to create our own exceptions which are basically derived classes of Exception. For example MyException in below code extends the Exception class.
We pass the string to the constructor of the super class- Exception which is obtained using “getMessage()” function on the object created. 







 


 

 













// A Class that represents use-defined expception 
class MyException extends Exception 
{ 
    public MyException(String s) 
    { 
        // Call constructor of parent Exception 
        super(s); 
    } 
} 
  
// A Class that uses above MyException 
public class Main 
{ 
    // Driver Program 
    public static void main(String args[]) 
    { 
        try
        { 
            // Throw an object of user defined exception 
            throw new MyException("GeeksGeeks"); 
        } 
        catch (MyException ex) 
        { 
            System.out.println("Caught"); 
  
            // Print the message from MyException object 
            System.out.println(ex.getMessage()); 
        } 
    } 
} 


















Output:


Caught

GeeksGeeks
In the above code, constructor of MyException requires a string as its argument.  The string is passed to parent class Exception’s constructor using super().   The constructor of Exception class can also be called without a parameter and call to super is not mandatory.







 


 

 













// A Class that represents use-defined expception 
class MyException extends Exception 
{ 
  
} 
  
// A Class that uses above MyException 
public class setText 
{ 
    // Driver Program 
    public static void main(String args[]) 
    { 
        try
        { 
            // Throw an object of user defined exception 
            throw new MyException(); 
        } 
        catch (MyException ex) 
        { 
            System.out.println("Caught"); 
            System.out.println(ex.getMessage()); 
        } 
    } 
} 


















Output:


Caught

null
This article is contributed by Pranjal Mathur. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
 













 


 

 
Most popular in Java
 



 

 
Most visited in School Programming
 


  


 













